package com.qufadai.framework.common.utils.json.serializer;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import com.qufadai.framework.common.utils.json.JsonStringSymbol;
import com.qufadai.framework.common.utils.json.Serializer;
import com.qufadai.framework.common.utils.json.support.JsonStringWriter;

public class CollectionSerializer implements Serializer {

	@Override
	public void convertTo(JsonStringWriter writer, Object obj)
			throws IOException {
		Collection<?> collection = (Collection<?>) obj;
		if (collection.size() == 0) {
			writer.write(JsonStringSymbol.EMPTY_ARRAY);
			return;
		}

		writer.append(JsonStringSymbol.ARRAY_PRE);
		for (Iterator<?> it = collection.iterator();;) {
			SerialStateMachine.toJson(it.next(), writer);
			if (!it.hasNext()) {
				writer.append(JsonStringSymbol.ARRAY_SUF);
				return;
			}
			writer.append(JsonStringSymbol.SEPARATOR);
		}

	}

}
